import { Component, OnInit } from '@angular/core';
import { getErrorQuestion, getErrorQuestionByTitle, getQuestionById } from '../api/api-all';

@Component({
  selector: 'app-page-error-question',
  templateUrl: './page-error-question.component.html',
  styleUrls: ['./page-error-question.component.scss']
})
export class PageErrorQuestionComponent implements OnInit {

  errorQuestionList: Array<any> = []


  ngOnInit(): void {
    this.initErrorQuestion()
  }

  formatQuestionList(questionEntity: any) {
    const list: Array<any> = this.errorQuestionList
    const qId: string = questionEntity.objectId
    const curIndex = list.findIndex(obj => obj.questionId === qId)
    if (curIndex >= 0) {
      list[curIndex].questionEntity = questionEntity
    }
  }

  search(input: any) {
    const reg = /^\s+|\s+$/g
    const key = input.target.value.replace(reg, '')

    if (key === null || key === "") {
      this.initErrorQuestion()
      return
    }  

    getErrorQuestionByTitle(key).then(res => {
      this.errorQuestionList = res
      for(let r of res) {
        getQuestionById(r.questionId).then(q => {
          this.formatQuestionList(q)
        })
      }
    })
  }

  initErrorQuestion() {
    getErrorQuestion().then(res => {
      this.errorQuestionList = res
      for(let r of res) {
        getQuestionById(r.questionId).then(q => {
          this.formatQuestionList(q)
        })
      }
    })
  }

}
